from flask import (
    Blueprint,
    request
)
from .forms import SMSCaptchaForm
from utils import restful, sms, redis_cach, img_path, common_util
import random
from apps.api.decorators import login_required, login_need
from datetime import datetime
import shortuuid
import os


bp = Blueprint("common", __name__, url_prefix="/common")


@bp.route('/captcha/', methods=['POST'])    # 验证码接口
def captcha():
    form = SMSCaptchaForm(request.form)
    if form.validate():
        phone = form.phone.data
        captcha_code_number = common_util.random_num(4)
        msg = "【自贸链壹】您的验证码是:{}".format(captcha_code_number)
        # print(phone, msg)
        send_captcha = sms.send_sms_captcha(phone, msg)
        if send_captcha is True:
            sms_code = 'sms_code_{}'.format(phone)
            sms_code_60 = 'sms_code_60_{}'.format(phone)
            redis_cach.sets(sms_code_60, 1, timeout=60)
            redis_cach.sets(sms_code, captcha_code_number, timeout=300)
            return restful.success(message='短信发送成功，请注意查收！')
        else:
            return restful.params_error(message='发送失败!请稍候再试')
    else:
        return restful.params_error(message=form.get_error())


@bp.route('/upload/', methods=['POST'])  # 上传图片接口
@login_need
def upload():
    file = request.files['file']
    if file:
        time_path = datetime.today().strftime('%Y%m%d')
        file_path = os.path.join('static/images/' + time_path)
        # file_path = os.path.join('/home/nginx/assets1/images/bbs/' + time_path)
        if not os.path.exists(file_path):
            os.mkdir(file_path)

        uuid = shortuuid.uuid()
        dir_path = os.path.join('static/images/' + time_path + '/', uuid + '.jpg')
        # dir_path = os.path.join('/home/nginx/assets1/images/bbs/' + time_path + '/', uuid + '.jpg')
        file.save(dir_path)
        file.close()
        img_paths = img_path() + dir_path
        return restful.success(data={'url': img_paths})
    else:
        return restful.params_error(message='请上传图片')
